<?php

class Group extends User_group_model {

    function __construct() {
        parent::__construct();
    }

    function getList($filter = array()) {
        $group = new Group();
        if(isset($filter['name']) && $filter['name']) {
            $group->addWhere("name LIKE '%".$filter['name']."%'");
        }
        $group->orderBy("name");
        $group->find();

        return $group;            
    }
    
    function validateInput() {

        if (empty ($this->name)) {
            MessageHandler::add (_MSG_NAME_NOT_EMPTY, MSG_ERROR, LOG_ONLY);
        }
        
        if (strlen($this->name) > MAX_LENGTH_NAME) {
            MessageHandler::add (_MSG_GROUP_NAME_IS_TOO_LONG, MSG_ERROR, LOG_ONLY);
        }
        
        if (self::isExistsByName($this->name, $this->id)) {
            MessageHandler::add (_MSG_GROUP_NAME_EXISTS, MSG_ERROR, LOG_ONLY);
        }
     
        return MessageHandler::countError() > 0 ? false : true;

    }
        
    public function isExistsByName($name = '', $id = 0)
	{
		if ($name == '')
		{
			return false;
		}	
		$group = new Group();
		
        if ($id) {
			$group->addWhere("id <> {$id}");
		}
                
        $group->addWhere("name = '$name'");
		$group->find();
		return ($group->countRows() > 0)?'1':'0';
	}
    
    public function allowAccess($id = 0, $value = 0) {
		$group = new Group();
		if (!$id || !$group->get($id) || $id == ADMIN) {
			return '0';
		}
		$group->allow_access = $value;
        $group->update();
		
		return '1';
	}
    
    function getPermission($group_ids) {
        $group = new Group();
        $group->addWhere("id IN (".$group_ids.") AND id <> ".ADMIN);
        $group->orderBy("name");
        $group->find();
        
        $group_names = array();
        while($group->fetchNext()) {
            $group_names[] = $group->name;
        }
        $group_name =  implode(', ', $group_names);
        if (!$group_name) {
            $group_name = _LB_NONE_GROUP;
        }
        return $group_name;
    }
}
